package be.teletask.onvif.parsers;

import be.teletask.onvif.models.GetAudioOutputConfiguration;
import be.teletask.onvif.responses.OnvifResponse;
import be.teletask.onvif.util.XmlToJsonUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Tomas Verhelst on 04/09/2018.
 * Copyright (c) 2018 TELETASK BVBA. All rights reserved.
 */
public class OnvifMediaAudioOutputConfigurationsParser extends OnvifParser<List<GetAudioOutputConfiguration>> {

    //Constants
    public static final String TAG = OnvifMediaAudioOutputConfigurationsParser.class.getSimpleName();

    @Override
    public List<GetAudioOutputConfiguration> parse(OnvifResponse response) {
        List<GetAudioOutputConfiguration> audioOutputConfigurations = new ArrayList<>();
        JSONObject bodyObjet = XmlToJsonUtils.xmlToJson(response.getXml());

        JSONArray configurationsArray = bodyObjet.getJSONObject("GetAudioOutputConfigurationsResponse").getJSONArray("Configurations");

        for (int i = 0; i < configurationsArray.size(); i++) {
            // 获取每个JSONObject
            JSONObject configurationObject = configurationsArray.getJSONObject(i);

            String token = configurationObject.getString("@token");
            String name = configurationObject.getString("Name");
            String outputToken = configurationObject.getString("OutputToken");
            String sendPrimacy = configurationObject.getString("SendPrimacy");
            Integer useCount = 0;
            if(configurationObject.containsKey("UseCount")) {
                useCount = configurationObject.getInteger("UseCount");
            }
            Integer outputLevel = configurationObject.getInteger("OutputLevel");
            GetAudioOutputConfiguration audioOutput = new GetAudioOutputConfiguration();
            audioOutput.setToken(token);
            audioOutput.setName(name);
            audioOutput.setOutputToken(outputToken);
            audioOutput.setSendPrimacy(sendPrimacy);
            audioOutput.setUseCount(useCount);
            audioOutput.setOutputLevel(outputLevel);

            audioOutputConfigurations.add(audioOutput);
        }

        return audioOutputConfigurations;
    }

}
